import { Input, Modal, Form, Select, Upload, message, Button, Icon, Checkbox } from "antd";
import { connect } from "dva";
import React, { PureComponent } from "react";
import TreeTransfer from "./TreeTransfer";
const { Option } = Select;

const PublishForm = Form.create({ name: 'publishModal' })(
    class extends React.Component {

        constructor(props){
            super(props)
            this.state = {
                showTransfer : false
            }
        }

        normFile = e => {
            console.log('Upload event:', e);
            if (Array.isArray(e)) {
              return e;
            }
            return e && e.fileList;
          };
            
        
        

        render() {

            const { 
                docListModalVisible,
                docListModalData,
                featureColumns,
                transferTargetKeys,
                transferTreeData,
                transferUserData
             } = this.props.docAssetsState
            const { getFieldDecorator } = this.props.form

            const formItemLayout = {
                labelCol: {
                    xs: { span: 24 },
                    sm: { span: 6 },
                },
                wrapperCol: {
                    xs: { span: 24 },
                    sm: { span: 16 },
                },
            };

            const uploadProps = {
                name: 'file', //参数名
                action: '/cwm/document/upload', //上传url
                onChange(info) {
                    if (info.file.status !== 'uploading') {
                        console.log(info.file, info.fileList);
                    }
                    if (info.file.status === 'done') {
                        message.success(`${info.file.name} 文件上传成功`);
                    } else if (info.file.status === 'error') {
                        message.error(`${info.file.name} 文件上传失败.`);
                    }
                },
            }

            const buildFormItem = (columnData) =>{
                const rules = []
                if(columnData.code === "docName"){
                    rules.push({required: true,
                        message: '请输入'+columnData.title,})
                }else if(columnData.code === "docType"){
                    rules.push({required: true,
                        message: '请选择'+columnData.title,})
                }
                return (<Form.Item label={columnData.title} key={columnData.id}>
                    {getFieldDecorator(columnData.dataIndex, {
                        rules: rules,
                        initialValue:docListModalData?docListModalData[columnData.dataIndex]:''
                    })(getFormItemContent(columnData))}
                    </Form.Item>
                )
            }

            const getFormItemContent =(columnData) =>{
                if(columnData.combId === "combobox"){ //下拉框
                    return (<Select style={{width:'100%'}}>
                        {
                            columnData.enumerationItems.map(item =>{
                                return (
                                    <Option
                                        title = {item.name}
                                        value = {item.id}
                                        key = {item.id}
                                    >{item.name}</Option>
                                )
                            })
                        }
                    </Select>)
                }else if(columnData.combId === "textfield"){//输入框
                    return (<Input/>)
                }
            }

            
            const isEdit = (docListModalData && docListModalData.instanceId && docListModalData.instanceId.length)
            return (
                <Modal
                    title={isEdit?'编辑':'发布'}
                    visible={docListModalVisible}
                    destroyOnClose = {true}
                    okText = {isEdit?'保存':'发布'}
                    cancelText = "取消"
                    afterClose={()=>{this.clearTransfer()}}
                    onCancel={() => this.props.dismissPublishModal()}
                    onOk={() => this.props.handleSave()}
                >
                    <Form {...formItemLayout} onSubmit={this.handleSubmit}>


                        {
                            featureColumns.map(value => {
                                return buildFormItem(value)
                            })
                        }

                        
                        {
                            !isEdit?
                            (<Form.Item label="文档上传" key='upload'
                            >
                            {getFieldDecorator('docUpload', {
                                rules: [],
                                valuePropName: 'fileList',
                                getValueFromEvent: this.normFile,
                            })(<Upload {...uploadProps}>
                                <Button>
                                    <Icon type="upload" /> 点击上传
                                </Button>
                            </Upload>)}
                        </Form.Item>):null
                        }

                        <Checkbox style={{marginLeft:20}} 
                        key='checkbox'
                        checked={this.state.showTransfer}
                        onChange={this.onCheckboxChange.bind(this)}>设置不可见用户</Checkbox>

                        {(this.state.showTransfer)? (<TreeTransfer
                        key='transfer'
                                style={{marginLeft:20,marginTop:20}}
                                    dataSource= {transferTreeData}
                                    transferDataSource = {transferUserData}
                                    showSearch
                                    targetKeys={transferTargetKeys}
                                    onChange={(targetKeys) => this.props.changeTransferTargetKeys(targetKeys)}
                                />):null
                                }
                    </Form>
                </Modal>
            )
        }

        onCheckboxChange(e){
            this.setState({
                showTransfer : e.target.checked
            })
        }

        clearTransfer(){
            this.setState({
                showTransfer : false
            })
            this.props.changeTransferTargetKeys([])
        }

        componentDidMount(){
            
            this.props.queryTransferData()
        }
    }
)

class DocAssetsPublishModel extends PureComponent {

    saveFormRef = formRef => {
        this.formRef = formRef;
      };

      handleSave = (docListModalData,transferTargetKeys) =>{
        const { form } = this.formRef.props;
        form.validateFields((err, values) => {
            if (err) {
              return;
            }
            console.log('Received values of form: ', values,docListModalData);
            let saveData = {...docListModalData}
            saveData.excludeUsersIds = transferTargetKeys
            for(let key in values){
                saveData[key] = values[key]
            }
            console.log('SaveData: ', saveData);
            this.props.saveModalData(saveData)
          });
      }

    render() {
        const { docAssetsState } = this.props
        const { docListModalData,transferTargetKeys } = docAssetsState
        return (
            <PublishForm
            wrappedComponentRef={this.saveFormRef}
            docAssetsState={docAssetsState}
            dismissPublishModal={this.props.dismissPublishModal}
            changeTransferTargetKeys = {this.props.changeTransferTargetKeys}
            queryTransferData = {this.props.queryTransferData}
            handleSave = {()=>this.handleSave(docListModalData,transferTargetKeys)}
            />
        )
    }


}

const mapState = (state) => {
    return {
        docAssetsState: {...state.docAssets}
    }
}

const mapDispatch = (dispatch) => {
    return {
        dismissPublishModal() {
            dispatch({
                type: 'docAssets/showPublishModal',
                payload: {docListModalVisible: false}
            })
            dispatch({
                type: 'docAssets/changePublishModalData',
                payload: {docListModalData: null}
            })
        },
        changeTransferTargetKeys(targetKeys){
            dispatch({
                type: 'docAssets/changeTransferTargetKeys',
                payload: {transferTargetKeys: targetKeys}
            })
        },
        queryTransferData(){
            dispatch({
                type: 'docAssets/queryOrgsAndUsers',
                payload: {}
            })
        },
        saveModalData(fileInfo){
            dispatch({
                type: 'docAssets/saveDocument',
                payload: {fileInfo}
            })
        }
    }
}

export default connect(mapState, mapDispatch)(DocAssetsPublishModel)